package com.cykj.user.python;

import com.alibaba.fastjson2.JSON;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.PumpStreamHandler;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

@Component
public class PythonExecutor {

    /**
     * 执行Python脚本
     * @param scriptPath 脚本路径(相对于项目根目录)
     * @param args 脚本参数
     * @return 脚本输出结果
     * @throws IOException 执行异常
     */
    public String execute(String scriptPath, String... args) throws IOException {
        // 构建命令
        CommandLine cmdLine = new CommandLine("python");
        cmdLine.addArgument(scriptPath);
        for (String arg : args) {
            cmdLine.addArgument(arg);
        }

        // 设置输出流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);

        // 执行命令
        DefaultExecutor executor = new DefaultExecutor();
        executor.setStreamHandler(streamHandler);
        int exitValue = executor.execute(cmdLine);

        if (exitValue != 0) {
            throw new IOException("Python脚本执行失败，退出码: " + exitValue);
        }

        return outputStream.toString().trim();
    }

    /**
     * 解析JSON数组
     * @param json JSON字符串
     * @return 解析后的Long列表
     */
    public List<Long> parseJsonArray(String json) {
        if (StringUtils.isBlank(json)) {
            throw new IllegalArgumentException("JSON字符串不能为空");
        }
        return JSON.parseArray(json, Long.class);
    }
}
